package io.renren.modules.pet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.exception.RenException;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.pet.dao.PetAdoptionDao;
import io.renren.modules.pet.dto.PetSendDTO;
import io.renren.modules.pet.enums.*;
import io.renren.modules.pet.service.PetSendService;
import io.renren.modules.pet.vo.PetAdoptionVO;
import io.renren.modules.pet.dto.PetAdoptionDTO;
import io.renren.modules.pet.entity.PetAdoptionEntity;
import io.renren.modules.pet.service.PetAdoptionService;
import io.renren.modules.pet.vo.PetSendVO;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.entity.DictData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 宠物领养申请表
 *
 * @author zwp zwp
 * @since 1.0.0 2025-03-15
 */
@Service
public class PetAdoptionServiceImpl extends CrudServiceImpl<PetAdoptionDao, PetAdoptionEntity, PetAdoptionVO> implements PetAdoptionService {

    @Autowired
    private PetSendService petSendService;

    @Override
    public QueryWrapper<PetAdoptionEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public void save(PetAdoptionDTO petAdoptionDTO) {
        PetAdoptionEntity petAdoptionEntity = ConvertUtils.sourceToTarget(petAdoptionDTO, PetAdoptionEntity.class);
        this.insert(petAdoptionEntity);
    }

    @Override
    public void update(PetAdoptionDTO petAdoptionDTO) {
        PetAdoptionEntity petAdoptionEntity = ConvertUtils.sourceToTarget(petAdoptionDTO, PetAdoptionEntity.class);
        this.updateById(petAdoptionEntity);
    }

    @Override
    public void savePetAdoption(PetAdoptionDTO dto) {
        PetSendVO petSendVo = petSendService.get(dto.getPetSendId());
        if (petSendVo == null) {
            throw new RenException("宠物不存在！");
        }
        if (petSendVo.getPetStatus() != 0) {
            throw new RenException("该宠物已被领养！");
        }
        if (petSendVo.getStatus() != 1) {
            throw new RenException("该宠物送养申请已被拒绝！");
        }
        // 获取当前用户
        Long userId = SecurityUser.getUserId();
        if (userId.compareTo(petSendVo.getCreator()) == 0) {
            throw new RenException("您不能领养自己的宠物！");
        }
        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("pet_send_id", dto.getPetSendId());
        wrapper.eq("applicant_id", userId);
        PetAdoptionEntity petAdoptionEntity = this.baseDao.selectOne(wrapper);
        if (petAdoptionEntity != null) {
            throw new RenException("您已报名成功！请勿重复报名！");
        }
        dto.setOwnerId(petSendVo.getCreator());
        dto.setApplicantId(userId);
        this.save(dto);
    }

    @Override
    public List<PetAdoptionVO> getByPetSendId(Long petSendId) {
        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("pet_send_id", petSendId);
        wrapper.ne("status", 2);
        List<PetAdoptionEntity> entityList = this.baseDao.selectList(wrapper);
        List<PetAdoptionVO> petAdoptionVoList = ConvertUtils.sourceToTarget(entityList, PetAdoptionVO.class);
        petAdoptionVoList.forEach(petAdoptionVo -> {
            petAdoptionVo.setApplicantAgeName(ApplicantAgeEnum.getChnByIndex(petAdoptionVo.getApplicantAge()));
            petAdoptionVo.setApplicantMarriageName(ApplicantMarriageEnum.getChnByIndex(petAdoptionVo.getApplicantMarriage()));
            petAdoptionVo.setApplicantHoursingName(ApplicantHoursingEnum.getChnByIndex(petAdoptionVo.getApplicantHoursing()));
            petAdoptionVo.setApplicantWorkStatusName(ApplicantWorkStatusEnum.getChnByIndex(petAdoptionVo.getApplicantWorkStatus()));
            petAdoptionVo.setApplicantPetsName(ApplicantPetsEnum.getChnByIndex(petAdoptionVo.getApplicantPets()));
            petAdoptionVo.setApplicantIncomeName(ApplicantIncomeEnum.getChnByIndex(petAdoptionVo.getApplicantIncome()));
        });
        return petAdoptionVoList;
    }

    @Override
    public void agreePetAdoption(PetAdoptionDTO dto) {
        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("pet_send_id", dto.getPetSendId());
        wrapper.eq("applicant_id", dto.getApplicantId());
        PetAdoptionEntity petAdoptionEntity = new PetAdoptionEntity();
        petAdoptionEntity.setStatus(1);
        this.baseDao.update(petAdoptionEntity, wrapper);

        PetSendDTO petSendDto = new PetSendDTO();
        petSendDto.setId(dto.getPetSendId());
        petSendDto.setPetStatus(1);
        petSendService.update(petSendDto);

    }

    @Override
    public void disagreePetAdoption(PetAdoptionDTO dto) {
        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", dto.getId());
        PetAdoptionEntity petAdoptionEntity = new PetAdoptionEntity();
        petAdoptionEntity.setStatus(2);
        this.baseDao.update(petAdoptionEntity, wrapper);
    }

    @Override
    public List<PetSendVO> getMyAdoptionPets(Map<String, Object> params) {
        String petBreed = (String)params.get("petBreed");
        String status = (String)params.get("status");
        // 获取当前用户
        Long userId = SecurityUser.getUserId();
        QueryWrapper<PetAdoptionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("applicant_id", userId);
        wrapper.eq("status", Integer.valueOf(status));
        List<PetAdoptionEntity> entityList = this.baseDao.selectList(wrapper);
        if (CollectionUtils.isEmpty(entityList)) {
            return Collections.emptyList();
        }
        List<Long> petSendIdList = entityList.stream().map(PetAdoptionEntity::getPetSendId).collect(Collectors.toList());
        List<PetSendVO> petSendVoList = petSendService.getListByIdList(petSendIdList);
        if (StringUtils.isNotBlank(petBreed)) {
            petSendVoList = petSendVoList.stream().filter(e -> e.getPetBreed().equals(Integer.valueOf(petBreed))).collect(Collectors.toList());
        }
        petSendVoList.forEach(petSendVo -> {
            // 首页图片
            petSendVo.setFirstImageUrl(petSendVo.getImageUrl().split(",")[0]);
        });
        return petSendVoList;
    }

}